import { VNode, h, inject, ref, watch } from "vue"
import { WebExcelCell } from "./cell"
import { checkTargetSlotIsEmpty, getValueByModel } from "./util"
import { ProvideEditStateKey } from "./keys"
import { EditComponent } from "./edit"

function WebExcelBody(props: Props, { slots }) {
    const result: any[] = []
    const lastEmptyRecord = ref({})
    const { checkDoingEdit } = inject(ProvideEditStateKey) as EditCellStateResult

    // 数据行
    props.dataSource?.forEach?.(createRowCells)

    // 可编辑时，创建最后的空行
    if (props.readonly !== true) {
        createEmptyRow()
    }

    // 创建行列
    function createRowCells(row: Object, rowindex: number){
        let isLastRow = props.readonly === true ? rowindex === props.dataSource.length - 1 : row === lastEmptyRecord.value;

        const cells = props.columns.map((column, colindex) => {
            return h(WebExcelCell, {
                class: {
                    'cell body': true,
                    'first-row': rowindex === 0,
                    'last-row' : isLastRow,
                    'row-first-cell': !props.showIndex && colindex === 0,
                    'row-last-cell' : colindex === props.columns.length - 1,
                },
                column: column,
                rowIndex: rowindex,
                colIndex: colindex,
                record: row,
            }, {
                default: () => {
                    const text = getValueByModel(column.dataIndex, row)

                    // slot
                    const slot = slots.bodyCell?.({ 
                        text, 
                        column, 
                        record: row,
                        index: rowindex,
                    })
                    if (!checkTargetSlotIsEmpty(slot)) return slot;

                    // column type is select or radio
                    const findOption = column.options?.find(opt => opt.value === text)
                    if (column.type && ['select', 'radio'].includes(column.type) && findOption) {

                        if (checkDoingEdit(rowindex, colindex)) return '';
                        
                        return findOption.label;
                    }

                    // column type is checkbox
                    if (column.type && ['checkbox'].includes(column.type) && Array.isArray(text)) {
                
                        if (checkDoingEdit(rowindex, colindex)) return '';

                        return text.map(v => {
                            return column.options?.find(opt => opt.value === v)?.label ?? v;
                        }).join('、')
                    }

                    // column type is radio
                    if (column.type && ['radio'].includes(column.type)) {
                        if (checkDoingEdit(rowindex, colindex)) return '';
                    }

                    // other
                    return text;
                },
                editCell: () => {
                    const props = {
                        column: column,
                        rowIndex: rowindex,
                        colIndex: colindex,
                        record: row,
                    }
                    return h(EditComponent, props, { editCell: slots.bodyEditCell })
                }
            })
        })

        if (props.showIndex) {
            cells.unshift(h(
                WebExcelCell, 
                {
                    class: {
                        'cell body row-index': true,
                        'first-row': rowindex === 0,
                        'last-row' : isLastRow,
                        'row-first-cell': true,
                        'row-last-cell' : props.columns.length === 0,
                    },
                    column: { readonly: true },
                    rowIndex: rowindex,
                    colIndex: undefined,
                    record: row,
                    isRowindex: true
                },
                {
                    default: () => rowindex + 1
                }
            ))
        }

        result.push(...cells)
    }

    // 创建最后的空行
    function createEmptyRow(){
        createRowCells(lastEmptyRecord.value, props.dataSource?.length)
        watch(() => Object.keys(lastEmptyRecord.value).length, (length) => {
            if (length) {
                props.dataSource.push({ ...lastEmptyRecord.value })
                lastEmptyRecord.value = {}
            }
        })
    }
    

    return result
}


export { WebExcelBody }